
import numpy as np
import pandas as pd

from datareport.api import ImageUtil
from datareport.api.annotation.Font import Font
from datareport.impl import StaticDF
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style

@style()
class ShiJi_KaiZhanChangCi_GaiLan_18(BaseParagraph):
    """
    实际概览
    """

    def __init__(self):
        super().__init__()
        self.text = '''本年度，各基层党支部实际累计开展组织生活{}场次，平均{}场次/支部/月'''
        self.fonts=[
            Font(text='本年度，各基层党支部实际累计开展组织生活'),

            Font(text='场次,',bold=True),
            Font(text='平均'),

            Font(text='场次/支部/月')
        ]
        self.sort = 9
        self.section = 2
        self.key_text=''

    def plot(self, df, plt):
        df=df.reset_index(drop=False)
        df['month'] = df['month'].astype(int)
        x_arr = np.arange(1, 13)
        for x in x_arr:
            if len(df[df['month'] == x]) == 0:
                df = df.append({'month': x, 'num': 0}, ignore_index=True)
        df.sort_values('month', inplace=True)
        df.rename(columns={"month": "月份", "num": "数量"}, inplace=True)
        df['月份'] = df['月份'].astype(str)
        df['月份']=df['月份'].values+'月'
        self.image=ImageUtil.plot(df,'本年度完成情况','','',rotation=0)

    def getData(self, df):
        pass

    def start(self, conn, year, plt):
        df = pd.read_sql('''select name,left(partyBranchName,2)partyBranchName,left(partyOrgName,2)partyOrgName,
        (select name from t_podict where value=t_meetinginfo.type) type,
        convert(month(createTime),char) month from t_meetinginfo  
                         where completeStatus='通过' and 
                         id in (select meetingInfoId from t_meetingrecord )
                        and year(startTime)={}'''.format(year), con=conn)
        avg = len(df) / (12 * len(df['partyBranchName'].drop_duplicates()))
        self.fonts.insert(1,Font(text=str(len(df)),bold=True))
        self.fonts.insert(-1,Font(text=str(round(avg,1))))
        df['num']=1
        StaticDF.data = df
        df=df[['month','num']].groupby('month')['num'].sum()
        self.plot(df,plt)


